package com.bhs.sansong.ui.wallet;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bhs.sansong.R;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.base.Constants;
import com.bhs.sansong.bean.PayInfo;
import com.bhs.sansong.bean.PayResult;
import com.bhs.sansong.bean.PayStatus;
import com.bhs.sansong.bean.UserInfo;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.main.MainActivity;
import com.bhs.sansong.ui.order.OrderDetailsActivity;
import com.bhs.sansong.utils.PayUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 收银台
 */
public class PayDeskActivity extends BaseActivity implements View.OnClickListener, NetCallBack {
    private TextView mTvTitle;
    private int payType = 2;//支付方式 1=线下支付 2=余额支付 3=支付宝支付 4=微信支付
    private int tradingHour = 15;//交易倒计时 分钟
    private LinearLayout mLlPayDesk;
    private LinearLayout mLlPaymentSuccess;
    private TextView mTvTradingHour;
    private TextView mTvMoney;
    private TextView mTvBalance;
    private ImageView mIvBalancePay;
    private TextView mTvBankCard;
    private ImageView mIvBankCardPay;
    private ImageView mIvAlipay;
    private ImageView mIvWeChat;
    private CheckBox mCbRedPacket;
    private Button mBtnSubmit;
    private Button mBtnBack;
    private String paySn;
    private TextView mTvPaySn;
    private Button mBtnCheckOrder;
    private String deliver_sn;
    private String pay_method;
    private LinearLayout mLlDisabled;
    private TextView mTvBalance2;
    private LinearLayout mLlAlipay;
    private LinearLayout mLlBalance;
    private IWXAPI msgApi;

    @Override
    public int initLayout() {
        return R.layout.activity_pay_desk;
    }

    @Override
    public void initView() {
        deliver_sn = getIntent().getStringExtra("deliver_sn");
        paySn = getIntent().getStringExtra("pay_sn");
        pay_method = getIntent().getStringExtra("pay_method");
        mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("结算");
        mLlPaymentSuccess = findViewById(R.id.ll_payment_success);
        mLlPayDesk = findViewById(R.id.ll_pay_desk);
        mTvTradingHour = findViewById(R.id.tv_trading_hour);
        mTvMoney = findViewById(R.id.tv_money);
        mTvBalance = findViewById(R.id.tv_balance);
        mIvBalancePay = findViewById(R.id.iv_balance_pay);
        mTvBankCard = findViewById(R.id.tv_bank_card);
        mIvBankCardPay = findViewById(R.id.iv_bank_card_pay);
        mIvAlipay = findViewById(R.id.iv_alipay);
        mIvWeChat = findViewById(R.id.iv_we_chat);
        mCbRedPacket = findViewById(R.id.cb_red_packet);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnBack = findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        findViewById(R.id.ll_we_chat).setOnClickListener(this);
        mLlAlipay = findViewById(R.id.ll_alipay);
        mLlAlipay.setOnClickListener(this);
        findViewById(R.id.ll_bank_card).setOnClickListener(this);
        mLlBalance = findViewById(R.id.ll_balance);
        mLlBalance.setOnClickListener(this);
        mTvPaySn = findViewById(R.id.tv_pay_sn);
        mBtnCheckOrder = findViewById(R.id.btn_check_order);
        mBtnCheckOrder.setOnClickListener(this);
        mLlDisabled = findViewById(R.id.ll_disabled);
        mTvBalance2 = findViewById(R.id.tv_balance2);
        msgApi = WXAPIFactory.createWXAPI(mActivity, null);
        // 将该app注册到微信
        msgApi.registerApp(Constants.APP_ID);
    }

    @Override
    public void initData() {
        if (TextUtils.isEmpty(pay_method) || pay_method.equals("1")) {
            networkRequest(netApi.get_user_info(), this, 9527);
            mTvPaySn.setText(String.format("伞送科技-%s", deliver_sn));
            mTvMoney.setText(String.valueOf(getIntent().getStringExtra("money")));
        } else {
            mLlPaymentSuccess.setVisibility(View.VISIBLE);
            mLlPayDesk.setVisibility(View.GONE);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_we_chat:
                payType = 4;
                setChecked(mIvWeChat);
                break;
            case R.id.ll_alipay:
                payType = 3;
                setChecked(mIvAlipay);
                break;
            case R.id.ll_balance:
                payType = 2;
                setChecked(mIvBalancePay);
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.btn_back:
                startActivity(new Intent(mActivity, MainActivity.class));
                break;
            case R.id.btn_check_order:
                startActivity(new Intent(mActivity, OrderDetailsActivity.class)
                        .putExtra("deliver_sn", deliver_sn));
                finish();
                break;
        }
    }

    private void submit() {
        Map<String, String> map = new ArrayMap<>();
        map.put("pay_sn", paySn);
        map.put("pay_type", String.valueOf(payType));//支付方式 4微信支付
        map.put("requet_type", "app");
        map.put("platform", "cargo");
        networkRequest(netApi.go_pay(map), this, 888);
    }

    private void setChecked(ImageView imageView) {
        mIvAlipay.setImageResource(R.mipmap.ic_unchecked);
        mIvBalancePay.setImageResource(R.mipmap.ic_unchecked);
        mIvWeChat.setImageResource(R.mipmap.ic_unchecked);
        mIvBankCardPay.setImageResource(R.mipmap.ic_unchecked);
        imageView.setImageResource(R.mipmap.ic_checked);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            UserInfo userInfo = new Gson().fromJson(json, UserInfo.class);
            if (userInfo.isStatus()) {
                mTvBalance.setText(String.format("可用余额%s元", userInfo.getData().getUser_info().getMoney01()));
                if (userInfo.getData().getUser_info().getWallet_status().equals("1")) {
                    mTvBalance2.setText(String.format("可用余额%s元", userInfo.getData().getUser_info().getMoney01()));
                    mLlAlipay.performClick();
                    mLlBalance.setVisibility(View.GONE);
                    mLlDisabled.setVisibility(View.VISIBLE);
                }
            }
        } else if (requestCode == 888) {
            PayInfo bean = new Gson().fromJson(json, PayInfo.class);
            if (bean.isStatus()) {
                if (payType == 2) {
                    deliver_sn = bean.getData().getPay_info().getDeliver_sn();
                    EventBus.getDefault().post(new PayStatus());
                    mLlPaymentSuccess.setVisibility(View.VISIBLE);
                    mLlPayDesk.setVisibility(View.GONE);
                } else if (payType == 4) {
                    PayUtils.weChatPay(mContext, bean.getData().getPay_params(), msgApi);
                } else if (payType == 3) {
                    Alipay(bean.getData().getOrderInfo());
                }
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    /**
     * 调起支付宝
     */
    private void Alipay(String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = 0;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult result = new PayResult((Map<String, String>) msg.obj);
            if (TextUtils.isEmpty(result.getResult())) {
                ToastUtil.show("支付失败");
            } else {
                finish();
            }

        }

    };
}